﻿using System;
using System.Linq;

using Whoever.Framework.CustomException;
using Whoever.Patterns.Business;

using EditorialProyectos.Business.Entities;
using EditorialProyectos.DataAccess.Repositories;
using System.Collections.Generic;

namespace EditorialProyectos.Business
{
    public class ActionPermissionManager : Manager<ActionPermission>
    {
        public ActionPermissionManager()
            : base(RepositoryFactory.ActionPermissionRepository)
        {
        }

        public Dictionary<string, bool> GetPermissions(string controllerName, User user)
        {
            var result = new Dictionary<string, bool>();
            var actions = Repository.QueryFactory.GetAll().Where(u => u.ContollerName == controllerName).ToList();

            foreach (var action in actions)
            {
                if (action.IsPublic)
                    result.Add(action.ActionName.ToLower(), true);
                else
                    result.Add(action.ActionName.ToLower(), HasPermission(controllerName, action.ActionName, user));
            }

            return result;
        }

        public bool HasPermission(string controllerName, string actionName, User user)
        {
            //var action = Repository.QueryFactory.GetAllRelated().FirstOrDefault(x => x.ContollerName.ToUpper().Equals(controllerName.ToUpper()) && x.ActionName.ToUpper().Equals(actionName.ToUpper()));

            //if (action != null)
            //{
            //    if (action.IsPublic)
            //        return true;

            //    var resultValue = user != null && user.RoleId != 0 && action.Roles.Where(u => u.Id == (string)user.RoleId).Count() > 0;
            //    return resultValue;
            //}

            throw new BusinessException("Unmanaged security");
        }
    }
}
